package com.sip.stream.utils.zfy.muxer;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.util.Log;

import com.sip.stream.ClientApp;
import com.sip.stream.R;
import com.sip.stream.media.ZFYMediaManager;
import com.sip.stream.rxbus.RxBus;
import com.sip.stream.utils.zfy.GSMediaSampleData;
import com.sip.stream.utils.zfy.RxBusTag;
import com.sip.stream.utils.zfy.VideoEncryptUtils;
import com.sip.stream.utils.zfy.ZFYMediaInfo;
import com.sip.stream.utils.zfy.event.ZFYMediaEvent;
import com.sip.stream.utils.zfy.status.ZFYStatus;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class GSMp4Muxer {
    private static final String TAG = "GSMp4Muxer";

    private MediaFormat cacheAudioformat;
    private MediaFormat cacheVideoformat;
    private long endTime;
    private Thread future;
    private MediaMuxer mediaMuxer;
    private ZFYPreRecordReader preRecordReader;
    private long startTime;
    private Disposable watchDisposable;
    private ZFYMediaInfo zfyMediaInfo;
    private int audioTrackIndex = -1;
    private int videoTrackIndex = -1;
    private AtomicBoolean isRecording = new AtomicBoolean();
    private BlockingDeque<GSMediaSampleData> waitDeque = new LinkedBlockingDeque(6000);
    private long lastVideoPresentationTimeUs = 0;
    private long lastFileSize = 0;

    public GSMp4Muxer(ZFYMediaInfo zFYMediaInfo) {
        if (setUpMediaInfo(zFYMediaInfo)) {
            Log.i(TAG, "mediaMuxer create success");
        } else {
            Log.e(TAG, "mediaMuxer create error");
        }
        this.startTime = System.currentTimeMillis();
    }

    public GSMp4Muxer(ZFYMediaInfo zFYMediaInfo, ZFYPreRecordReader zFYPreRecordReader) {
        this.preRecordReader = zFYPreRecordReader;
        String str = TAG;
        Log.i(str, "has preRecordReader");
        if (setUpMediaInfo(zFYMediaInfo)) {
            Log.i(str, "mediaMuxer create success");
        } else {
            Log.e(str, "mediaMuxer create error");
        }
        this.startTime = System.currentTimeMillis();
    }

    private boolean setUpMediaInfo(ZFYMediaInfo zFYMediaInfo) {
        this.zfyMediaInfo = zFYMediaInfo;
        try {
            this.mediaMuxer = new MediaMuxer(zFYMediaInfo.getFilepath(), 0);
            startWatchTask();
            try {
                this.mediaMuxer.setLocation((float) ZFYStatus.getInstance().getLocation().getLatitude(), (float) ZFYStatus.getInstance().getLongitude());
                return true;
            } catch (Exception unused) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            RxBus.getDefault().post("", RxBusTag.RECORDING_EXCEPTION);
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_ERROR", (int) R.string.meida_error_save_video), RxBusTag.MEDIA_EVENT);
            return false;
        }
    }

    public boolean addVideoTrack(MediaFormat mediaFormat) {
        MediaMuxer mediaMuxer;
        if (mediaFormat == null || (mediaMuxer = this.mediaMuxer) == null) {
            return false;
        }
        if (this.videoTrackIndex >= 0) {
            return true;
        }
        this.videoTrackIndex = mediaMuxer.addTrack(mediaFormat);
        this.cacheVideoformat = mediaFormat;
        Log.i(TAG, "addVideoTrack" + this.videoTrackIndex + "" + mediaFormat.toString());
        start();
        return true;
    }

    public boolean addAudioTrack(MediaFormat mediaFormat) {
        MediaMuxer mediaMuxer;
        if (mediaFormat == null || (mediaMuxer = this.mediaMuxer) == null) {
            return false;
        }
        if (this.audioTrackIndex >= 0) {
            return true;
        }
        this.audioTrackIndex = mediaMuxer.addTrack(mediaFormat);
        this.cacheAudioformat = mediaFormat;
        Log.i(TAG, "addAudioTrack" + this.audioTrackIndex + "" + mediaFormat.toString());
        start();
        return true;
    }

    public synchronized void start() {
        if (this.audioTrackIndex >= 0 && this.videoTrackIndex >= 0) {
            Log.i(TAG, "start");
            if (this.isRecording.get()) {
                return;
            }
            Single.just(Boolean.TRUE).observeOn(AndroidSchedulers.mainThread()).doOnSuccess(new Consumer() {
                @Override
                public  void accept(Object obj) {
                    if (GSMp4Muxer.this.audioTrackIndex < 0 || GSMp4Muxer.this.videoTrackIndex < 0) {
                        return;
                    }
                    Log.i(TAG, "start");
                    if (GSMp4Muxer.this.isRecording.get()) {
                        return;
                    }
                    GSMp4Muxer.this.mediaMuxer.start();
                    GSMp4Muxer.this.isRecording.set(true);
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public  void run() {
                            GSMp4Muxer.this.m514xa91f25b5();
                        }
                    });
                    GSMp4Muxer.this.future = thread;
                    thread.start();
                }
            }).subscribe(new SingleObserver<Boolean>() {
                @Override
                public void onSubscribe(Disposable disposable) {
                }

                @Override
                public void onSuccess(Boolean bool) {
                }

                @Override
                public void onError(Throwable th) {
                    th.printStackTrace();
                }
            });
        }
    }



    private void restartWhenError() {
        if (!this.isRecording.get() || this.cacheVideoformat == null || this.cacheAudioformat == null) {
            return;
        }
        this.mediaMuxer.release();
        this.mediaMuxer = null;
        try {
            this.mediaMuxer = new MediaMuxer(this.zfyMediaInfo.getFilepath(), 0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.videoTrackIndex = this.mediaMuxer.addTrack(this.cacheVideoformat);
        this.audioTrackIndex = this.mediaMuxer.addTrack(this.cacheAudioformat);
        this.mediaMuxer.start();
    }

    public boolean canStop() {
        if (this.isRecording.get()) {
            return true;
        }
        Log.w(TAG, "canStop false videoTrackIndex " + this.videoTrackIndex + " audioTrackIndex " + this.audioTrackIndex);
        return System.currentTimeMillis() - this.startTime > 5000;
    }

    public void m514xa91f25b5() {
        while (true)
        {
            try {
                GSMediaSampleData readNextSampleData = readNextSampleData();
                if (readNextSampleData.getBufferInfo().flags == 4)
                {
                    break;
                } else if (readNextSampleData.getBufferInfo().flags != 2)
                {
                    try {
                        if (readNextSampleData.getPresentationTimeUs() < 1)
                        {
                            Log.w(TAG, "write timestamp error presentationTimeUs: " + readNextSampleData.getBufferInfo().presentationTimeUs + " flags: " + readNextSampleData.getBufferInfo().flags);
                        } else {
                            this.mediaMuxer.writeSampleData(readNextSampleData.isAudio() ? this.audioTrackIndex : this.videoTrackIndex, readNextSampleData.getByteBuf(), readNextSampleData.getBufferInfo());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e(TAG, "writeSampleData error " + e.getMessage());
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                Log.e(TAG, "readNextSampleData");
            }
            releaseMp4();
        }
        Log.e(TAG, "BUFFER_FLAG_END_OF_STREAM");
        releaseMp4();
    }

    private GSMediaSampleData readNextSampleData() throws InterruptedException {
        if (this.preRecordReader != null) {
            GSMediaSampleData readNextSampleDataAction = this.preRecordReader.readNextSampleDataAction();
            if (readNextSampleDataAction == null) {
                this.preRecordReader = null;
                return this.waitDeque.take();
            }
            Log.d(TAG, "preRecord Reader" + (readNextSampleDataAction.isAudio() ? " audio " : " video ") + readNextSampleDataAction.getBufferInfo().presentationTimeUs);
            return readNextSampleDataAction;
        }
        return this.waitDeque.take();
    }

    public synchronized void releaseMp4() {
        String filename;
        stopWatchTask();
        if (this.mediaMuxer == null) {
            Log.e(TAG, "mediaMuxer == null");
            return;
        }
        Log.i(TAG, "releaseMp4 " + this.zfyMediaInfo.getFilepath());
        new File(this.zfyMediaInfo.getFilepath());
        try {
            this.mediaMuxer.stop();
            this.mediaMuxer.release();
            this.waitDeque = null;
            this.mediaMuxer = null;
            File file = new File(this.zfyMediaInfo.getFilepath());
            String[] split = this.zfyMediaInfo.getFilename().split("\\.");
            if (split.length > 1) {
                filename = split[0];
            } else {
                filename = this.zfyMediaInfo.getFilename();
            }
            if (ZFYMediaManager.getInstance().getStatus().isImportantAndUse()) {
                filename = addImpMark(filename);
            }
            String str2 = filename + ".mp4";
            String replace = this.zfyMediaInfo.getFilepath().replace(this.zfyMediaInfo.getFilename(), str2);
            Log.i(TAG, "rename to " + replace + " result " + (file.renameTo(new File(replace)) ? "true" : "false"));
            this.zfyMediaInfo.setFilepath(replace);
            this.zfyMediaInfo.setFilename(str2);
            this.zfyMediaInfo.setComplete(true);
            this.zfyMediaInfo.setFilesize(file.length());
            this.zfyMediaInfo.setDuration(this.startTime - this.endTime);
            if (ZFYMediaManager.getInstance().getConfig().getVideoEncrypt() == 1) {
                VideoEncryptUtils.encrypt(replace);
            } else {
                MediaScannerConnection.scanFile(ClientApp.clientApp, new String[]{replace}, new String[]{"video/mp4"}, new MediaScannerConnection.OnScanCompletedListener() {
                    @Override
                    public void onScanCompleted(String str3, Uri uri) {
                    }
                });
            }
            if (!ZFYMediaManager.getInstance().getStatus().isVideoStart()) {
                ZFYMediaManager.getInstance().getStatus().setImportant(false);
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
            if (!ZFYMediaManager.getInstance().getStatus().isVideoStart() && !ZFYMediaManager.getInstance().getStatus().isRemoteVideoAndAudio()) {
                RxBus.getDefault().post(new ZFYMediaEvent(ZFYMediaEvent.EVENT_TYPE_VIDEO_STOP_COMPLETE), RxBusTag.MEDIA_EVENT);
            }
            RxBus.getDefault().post("", RxBusTag.RECORDING_EXCEPTION);
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_ERROR", (int) R.string.meida_error_save_video), RxBusTag.MEDIA_EVENT);
            try {
                File file2 = new File(this.zfyMediaInfo.getFilepath());
                if (file2.length() < 1048576) {
                    file2.delete();
                }
            } catch (Exception es) {
                es.printStackTrace();
            }
        }
    }

    private String addImpMark(String filePath) {
        return "IMP_" + filePath;
    }

    private String addImpMark_GXGA(String filePath) {
        return filePath.replace("NOR", "IMP");
    }

    public void stop() {
        this.endTime = System.currentTimeMillis();
        stopAction();
    }

    private void stopAction() {
        this.isRecording.set(false);
        if (this.future != null) {
            GSMediaSampleData gSMediaSampleData = new GSMediaSampleData();
            MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
            bufferInfo.flags = 4;
            gSMediaSampleData.setBufferInfo(bufferInfo);
            Log.d("Linzy", "write BUFFER_FLAG_END_OF_STREAM");
            writeSampleData(gSMediaSampleData);
            return;
        }
        releaseMp4();
    }

    public boolean writeSampleData(GSMediaSampleData gSMediaSampleData) {
        try {
            this.waitDeque.offer(gSMediaSampleData);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "" + e.getLocalizedMessage());
            releaseMp4();
            e.printStackTrace();
            return true;
        }
    }

    private void startWatchTask() {
        stopWatchTask();
        Observable.interval(60L, TimeUnit.SECONDS).subscribeOn(Schedulers.newThread()).subscribe(new Observer<Long>() {
            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable th) {
            }

            @Override
            public void onSubscribe(Disposable disposable) {
                GSMp4Muxer.this.watchDisposable = disposable;
            }

            @Override
            public void onNext(Long l) {
                String filepath = GSMp4Muxer.this.zfyMediaInfo.getFilepath();
                Log.i(TAG, "startWatchTask : " + filepath);
                File file = new File(filepath);
                if (!file.exists()) {
                    GSMp4Muxer.this.stopWatchTask();
                    return;
                }
                long length = file.length();
                if (length - GSMp4Muxer.this.lastFileSize < 100) {
                    RxBus.getDefault().post("", RxBusTag.RECORDING_EXCEPTION);
                    GSMp4Muxer.this.stopWatchTask();
                }
                GSMp4Muxer.this.lastFileSize = length;
            }
        });
    }

    public void stopWatchTask() {
        Disposable disposable = this.watchDisposable;
        if (disposable != null) {
            disposable.dispose();
            this.watchDisposable = null;
        }
    }
}
